
const Delfin = (() => {
  const watcher = {
    /*
    title:{
      collection:[h1,h2],
      cb:callback
    },
    content:{
      collection:[p,span],
      cb:callback
    }
    */
  };

  function useReactive(state) {
    return new Proxy(state, {
      get(target, key) {
        return Reflect.get(target, key);
      },
      set(target, key, value) {
        update(watcher[key].collection, value);
        watcher[key].cb(target[key], value);
        return Reflect.set(target, key, value);
      },
    });
  }

  function useWatcher(collection, key, callback) {
    !watcher[key] && (watcher[key] = {});
    !watcher[key].collection && (watcher[key].collection = []);

    watcher[key].cb = callback;
    watcher[key].collection = [...watcher[key].collection, ...collection];
    console.log(watcher);
  }

  function update(collection, value) {
    collection.forEach((item) => {
      item.innerText = value;
    });
  }

  return {
    useReactive,
    useWatcher,
  };
})();

const { useReactive, useWatcher } = Delfin;
const state = useReactive({
  title: "This is TITLE",
  content: "This is CONTENT",
});

useWatcher(
  [document.querySelector("h1"), document.querySelector("h2")],
  "title",
  (prev, cur) => {
    console.log(prev, cur);
  }
);

useWatcher(
  [document.querySelector("p"), document.querySelector("span")],
  "content",
  (prev, cur) => {
    console.log(prev, cur);
  }
);

function render() {
  document.querySelector("h1").innerText = state.title;
  document.querySelector("h2").innerText = state.title;
  document.querySelector("p").innerText = state.content;
  document.querySelector("span").innerText = state.content;
}

render();

setTimeout(() => {
  state.title = "new TITLE";
  state.content = "new CONTENT";
}, 1500);

const logColor = (color, args) => {
  console.log("%c" + args, "color:" + color);
};
const log = {
  success: (...args) => logColor("green", args),
  info: (...args) => logColor("gery", args),
  warring: (...args) => logColor("orange", args),
  error: (...args) => logColor("red", args),
};
log.success("Hello Word!");
log.info("Hello Word!");
log.warring("Hello Word!");
log.error("Hello Word!");
